//实现了一个图片上传和管理组件

import React, { useState, useCallback, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Upload, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { BASE_IMG_URL, UPLOAD_IMG_NAME } from '../../utils/constants';
import { reqDeleteImg } from '../../api';
import PropTypes from 'prop-types';

const PicturesWall = forwardRef(({ imgs = [] }, ref) => {
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [fileList, setFileList] = useState([]);

  // 初始化文件列表
  useEffect(() => {
    if (imgs.length > 0) {
      const newFileList = imgs.map((img, index) => ({
        uid: `-${index}`,
        name: img,
        status: 'done',
        url: BASE_IMG_URL + img,
      }));
      setFileList(newFileList);
    }
  }, [imgs]);

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    getImgs: () => fileList.map(file => file.name),
  }), [fileList]);

  // 关闭大图预览
  const handleCancel = useCallback(() => {
    setPreviewVisible(false);
  }, []);

  // 预览大图
  const handlePreview = useCallback((file) => {
    setPreviewImage(file.url || file.thumbUrl);
    setPreviewVisible(true);
  }, []);

  // 处理文件变化
  const handleChange = useCallback(async ({ file, fileList: newFileList }) => {
    // 上传成功时
    if (file.status === 'done') {
      const { status, data } = file.response || {};
      if (status === 0) {
        message.success('上传成功');
        // 更新当前最新上传的文件信息
        const lastIndex = newFileList.length - 1;
        newFileList[lastIndex].name = data.name;
        newFileList[lastIndex].url = data.url;
      } else {
        message.error('上传失败');
      }
    } else if (file.status === 'removed') {
      // 删除图片时
      try {
        const result = await reqDeleteImg(file.name);
        if (result.status === 0) {
          message.success('删除图片成功');
        } else {
          message.error('删除图片失败');
        }
      } catch (error) {
        console.error('删除图片时出现错误:', error);
        message.error('网络请求失败');
      }
    }
    setFileList([...newFileList]);
  }, []);

  //定义上传按钮
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div>上传图片</div>
    </div>
  );

  return (
    <div>
      <Upload
        action="/manage/img/upload"
        accept="image/*"
        name={UPLOAD_IMG_NAME}
        listType="picture-card"
        fileList={fileList}
        onPreview={handlePreview}
        onChange={handleChange}
      >
        {fileList.length >= 8 ? null : uploadButton}
      </Upload>
      <Modal open={previewVisible} footer={null} onCancel={handleCancel}>
        <img alt="preview" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </div>
  );
});

PicturesWall.propTypes = {
  imgs: PropTypes.array,
};

export default PicturesWall;
